<template>
    <div class="bc-input-number">
        <div @click="reduce" class="bc-input-number__icon bc-input-number__reduce">
            <bc-icon size="30px" name="bc-remove-circle" />
        </div>
        <input @change="inputChange" ref="input" type="text" :value="value" class="bc-input-number__input" />
        <div @click="add" class="bc-input-number__icon bc-input-number__add">
            <bc-icon size="30px" name="bc-add-circle" />
        </div>
    </div>
</template>

<script>
import BcIcon from '@/components/icon/index.js'
export default {
    name: 'BcInputNumber',
    components: {
        BcIcon
    },
    props: {
        value: [Number, String],
        step: {
            type: Number,
            default: 1
        },
        max: [Number, String],
        min: [Number, String]
    },
    data() {
        return {
            oldVal: 0,
            userInput: null,
        }
    },
    methods: {
        add() {
            let num = Number(this.value) + this.step;
            this.emitVal(num)
        },
        reduce() {
            let num = Number(this.value) - this.step;
            this.emitVal(num)
        },
        inputChange(event) {
            this.emitVal(Number(event.target.value));
        },
        emitVal(num) {
            let min = this.min;
            let max = this.max;
            if(max !== undefined && num > max) num = max;
            if(min !== undefined && num < min) num = min;
            
            // 不通过父组件修改value属性值来修改input的值，而是直接修改。
            this.$refs.input.value = num
            if(num === this.oldVal) return;
            this.oldVal = num;
            // 通过emit让value与input的实际value同步
            this.$emit("input", num);
            this.$emit("change", num);
            // 在做加减操作时先生成新值，通过emit传给父组件，父组件改变props值传给这个组件的value变量，value变量再改变input框实际的value。
            // 所以在下一步打印input实际的value和this.value时还是上一次的值。
            // 而change事件出发的修改步骤为：直接改变input框的实际value值，传给父级再传回来，改变this.value，进而改变input实际的value。
            // 但input实际的value一开始就被改变了，后来又被改变一次，两次值一样。
            // console.log("this.value", this.value)
            // console.log("input value", this.$refs.input.value)
        }
    }
}
</script>

<style scoped>
.bc-input-number {
    position: relative;
    display: inline-block;
    width: 160px;
    height: 36px;
    border: 1px solid #000;
    box-sizing: content-box;
}
.bc-input-number>.bc-input-number__icon {
    position: absolute;
    top: 2px;
    cursor: pointer;
}
.bc-input-number>.bc-input-number__reduce {
    left: 5px;
}
.bc-input-number>.bc-input-number__add {
    right: 5px;
}
.bc-input-number>.bc-input-number__input {
    display: block;
    width: 100%;
    height: 100%;
    padding-left: 44px;
    padding-right: 44px;
    box-sizing : border-box;
    border: none;
    outline: none;
    text-align: center;
    font-size: 14px;
}
.bc-input-number>.bc-input-number__icon:active {
  opacity: 0.7;
  transform: scale(0.9);
}
</style>